<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Building photo controller
 */
class Building extends Front_Controller
{

    private $_defaultChannel = 'other';

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function index() {
        if (is_fang90_server_name()) redirect(config_item('fang90.domain'));
    }

    /**
     * Display a list of Buildings data.
     *
     * @return void
     */
    public function detail($city = '', $buildingId = 1616, $offset = 0) {

        // fang90 楼盘id处理
        // $extNumber = 792103483961;
        // if ($buildingId > $extNumber && !is_fang90_server_name()) $buildingId = $buildingId - $extNumber;

        $get = $this->input->get();
        $channel = (isset($get['qd']) && !empty($get['qd'])) ? $get['qd'] : $this->_defaultChannel;
        $hp_version = (isset($get['hv']) && !empty($get['hv'])) ? $get['hv'] : "v1";
        $magic = (isset($get['magic']) && !empty($get['magic'])) ? $get['magic'] : null;
        // 处理渠道中多余的问号
        if (stripos($channel, '?') !== false) {
            $channel = explode('?', $channel)[0];
        }
        $targetCity = (isset($get['target_city']) && !empty($get['target_city'])) ? $get['target_city'] : '';
        // 处理目标城市多余的问号
        if (stripos($targetCity, '?') !== false) {
            $targetCity = explode('?', $targetCity)[0];
        }
        // 加载模型
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingshuxing_model');
        $this->load->model('buildings/buildingsinfo_model');
        $this->load->model('buildings/photos_model');
        $this->load->model('buildings/buildingstag_model');
        $this->load->model('vendor/vendor_model');
        $this->load->model('phone/phone_model');
        $this->load->model('channel/channel_model');
        //$this->load->driver('cache');
        $this->load->library('user_agent');
        //刷新浏览量
        // $this->cache->redis->increment("brower_index_".$buildingId);
        // 读取数据
        $building = $this->buildings_model->getBuildingById($buildingId); //getBuildingByCode('xxtkqc');
        if ($building->deleted == 1 && $get['view'] != 1) is_fang90_server_name() ? redirect("http://fang90.com") : redirect("/");
        $info = $this->buildingsinfo_model->getInfoByBuildingId($building->id);
        if ($info->price_desc != '') {
            $price = $info->price_desc;
            $number =preg_replace('/\D/s', '', $price);
            //dump($number);exit;
            $classText = is_fang90_server_name() ? '' : 'class="text-primary"';
            $info->price_desc = str_replace($number, '<span '.$classText.'>¥'.number_format($number)."</span>", $price);
            //dump($info->price_desc);exit;
        }
        // 楼盘期数与名称拼接
        if(!empty($building->nickname)){
            $building->name = $building->nickname;
        }
        $photos = $this->buildings_model->getBuildingPhotos($building->id);
        //获取对应楼盘的户型id
        $huxing = [];
        $huxing_ids = $this->buildingshuxing_model->where("building_id = {$buildingId} and deleted = 0")->find_all();
        if ($huxing_ids) {
            foreach ($huxing_ids as $key => $value) {
                $huxing[$key] = $this->buildings_model->getHuXingBuildingPhotos($value->building_id,$value->id);
            }
        }

        $tags = $this->buildingstag_model->tags($building->id);
        $vendor = $this->vendor_model->findById($building->developer_id);
        $phone = $this->phone_model->getPhoneByBuildingId($building->id, $channel);
        if (in_array($building->id, [1638,1684])) {
            // 1638 绿地美国,1684 绿地伦敦 楼盘特殊处理分机号
            $phone = $this->_ext_target_city($building->id, $channel, $targetCity);
        }
        $building->info = $info;
        $building->photos = $photos;
        //顶部图版本处理
        if(isset($photos['lpdb']) && !empty($hp_version) ){
            $lpdb_pc = $photos['lpdb']['pc'];
            $lpdb_mobile = $photos['lpdb']['mobile'];
            $photos['lpdb']['pc'] = [];
            $photos['lpdb']['mobile'] = [];
            foreach ($lpdb_pc as $key => $value) {
                if($value->version == $hp_version){
                    $photos['lpdb']['pc'][] = $value;
                    $photos['lpdb']['mobile'][] = $lpdb_mobile[$key];
                }
            }
            if(empty($photos['lpdb']['pc'])){
                $photos['lpdb']['pc'][] = $lpdb_pc[0];
                $photos['lpdb']['mobile'][] = $lpdb_mobile[0];
            }
            $building->photos = $photos;
            
        }
        // 魔方网页、多个版本 处理
        if(isset($photos['tstp']['pc'])){
            $isMagic = false;
            foreach ($photos['tstp']['pc'] as $key => $value) {
                if($value->version == 'v2'){
                    $isMagic = true;
                    break;
                }
            }
            // 魔方网页
            if ($isMagic && $magic) $building->photos = $this->magicPage($photos, $buildingId, $hp_version);
            // 特色图片多个版本
            if ($isMagic && !$magic) $building->photos = $this->tstpVersion($photos, $hp_version);
            // dump($building->photos['tstp']);exit();
        }
        $building->ave_price = number_format($building->ave_price);
        $building->tag = $tags;
        $building->vendor = $vendor;
        $building->phone = $phone;
        $building->huxing = $huxing;
        $building->channel_id = $phone ? $phone['pc']->channel_id : 0;
        if ($building->id == 1633) {
            $building->open_time = "预计2016年6月";
        }
        
        //dump($phone);

        $isUCBrowser = stripos($this->agent->agent, 'UCBrowser') !== false;
        $data['is_mobile'] = $this->agent->is_mobile();
        $data['is_pad'] = stripos($this->agent->mobile, 'pad') === false ? 0 : 1;
        $data['building'] = $building;
        $data['channel'] = $channel;
        //$data['view_log'] = $this->viewBuildingLog($building, $channel);
        $data['ip_address'] = $this->ip_address;
        $data['related_items'] = $info->building_switch==1 ? $this->buildings_model->getRelatedItemsById($buildingId) : '';
        $data['is_ie'] = ($this->agent->browser=='Internet Explorer' || $isUCBrowser) ? 1 : 0;
        $hasChannel = $this->channel_model->count_by('code', $channel);
        $data['show_qyyx58'] = ($this->agent->is_mobile() && !in_array($channel, ['baidu', 'bd1', 'bd', 'bdka', 'other']) && $hasChannel) ? 1 : 0;
        $data['city_code'] = $city;
        $ms = date("Hi");
        if ($this->agent->is_mobile() 
            && in_array($channel, ['baidu', 'bd1', 'bd']) 
            && (($ms >= 1830 && $ms <= 2359) || ($ms >= 0 && $ms <= 0859) || in_array(date("N"), [6,7]))) {
            // 这个条件下百度相关渠道
            $data['show_qyyx58'] = 1;
        }
        if ($this->agent->is_mobile()) {
            // 暂时全部渠道可以
            $data['show_qyyx58'] = 1;
        }
        $this->load->view('front/building/campaign', $data);
        // if (is_udfang_server_name() && $building->id != 1691 ) $this->load->view('front/building/campaign', $data);
        // else $this->load->view('front/building/index', $data);
    }

    /**
     * 发送售楼地址接口
     * @return string
     */
    public function sendAddress() {
        $get = $this->input->get();
        $mobile = $get['mobile'];
        $buildingId = $get['building_id'];
        $telExt = $get['tel_ext'];
        $phoneCode = $get['phone_code'];

        if (!$this->verifyMobile($mobile)) {
            echo '号码错误';
            exit;
        }

        // 加载模型
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingsinfo_model');
        // 楼盘数据
        $building = $this->buildings_model->getBuildingById($buildingId);

        // 判断是否需要手机验证码功能，现在只有北京的项目有这个功能

        if ($this->isShowPhoneAuthCode($building->city_id, $mobile)) {
            if (empty($phoneCode)) {
                // $this->sendCode($mobile);
                exit('auth_code');
            } else {
                // 验证是否正确
                if (!$this->verifyPhoneCode($mobile, $phoneCode)) {
                    exit("验证码错误~");
                }
            }
        }

        if (!empty($building)) {
            $info = $this->buildingsinfo_model->getInfoByBuildingId($building->id);
            if (is_fang90_server_name()) {
                // fang90 域名处理
                $building->telephone = 4006812598;
            }
            // 发送短信
            $content = "【".$building->name."】 楼盘地址：".$info->address."，咨询电话：".$building->telephone."转".$telExt."，流水号：".time()."。";
            if (is_fang90_server_name()) {
                $content = str_replace(['【', '】'], ['[', ']'], $content);
            }
            $rebackCode = $this->sendSMS($mobile, $content);
            if($rebackCode->code == 2){
                    // 写记录
                    $this->load->model('buildings/buildingsyuyue_model');
                    $this->buildingsyuyue_model->insert(array('building_id'=>$buildingId, 'building_code'=>$building->code, 'telphone'=>$mobile, 'type'=>3));
                    echo 'ok';
            }else{
                    echo 'error';
            }
           
        }
    }

     //变价通知（type=4）和优惠通知（type=5）
    public function savePhone() {
        $get = $this->input->get();
        $mobile = $get['mobile'];
        $buildingId = $get['building_id'];
        $action = $get['action'];

        if (!$this->verifyMobile($mobile)) {
            echo '号码错误';
            exit;
        }
        // 加载模型
        $this->load->model('buildings/buildings_model');
        // 楼盘数据
        $building = $this->buildings_model->getBuildingById($buildingId);
        if (!empty($building)) {
            // 写记录
            $this->load->model('buildings/buildingsyuyue_model');
            $this->buildingsyuyue_model->insert(array('building_id'=>$buildingId, 'building_code'=>$building->code, 'telphone'=>$mobile, 'type'=>$action));
            echo 'ok';
        }
    }
    /**
     * 发送400电话接口，电话咨询
     * @return string 
     */
    public function sendCcic2Zixun() {
        $get = $this->input->get();
        $mobile = $get['mobile'];
        $telExt = $get['tel_ext'];
        $buildingId = $get['building_id'];
        $captcha = isset($get['captcha']) ? $get['captcha'] : null;
        $phoneLogId = $get['phone_log_id'];
        $cookieName = 'udf_ccic2_call_'.$buildingId.'_'.$mobile;
        // 加载模型
        $this->load->model('buildings/buildings_model');
        $this->load->helper('cookie');

        if (!$this->verifyMobile($mobile)) {
            echo '号码错误';
            exit();
        }

        // 楼盘数据
        $building = $this->buildings_model->getBuildingById($buildingId);

        // 判断是否需要手机验证码功能，现在只有北京的项目有这个功能
        if ($this->isShowPhoneAuthCode($building->city_id, $mobile)) {
            // $this->sendCode($mobile);
            exit('auth_code');
        }

        if (empty($captcha)) {
            $cookie = get_cookie($cookieName);
            if ($cookie) {
                // 需要验证码
                echo 'yzm';
                exit();
            }
        } else {
            if (strtolower($captcha) != strtolower($this->session->userdata('captcha_code'))) {
                // 验证码错误
                echo 'yzm_error';
                exit();
            }
        }

        if ($building) {
            // 400 异步调用
            $userField = urlencode("from=hiswift&building_code={$building->code}&phone_log_id={$phoneLogId}");
            $clidNumber = $this->clidNumber($building->city_id);
            $returnJson = $this->ccic2($mobile, $telExt, $userField, $clidNumber);
            // $returnData = json_decode($returnJson);
            // if ($returnData->result == 1) {
                // 成功，写记录
                $this->load->model('buildings/buildingsyuyue_model');
                $this->buildingsyuyue_model->insert(array('building_id'=>$buildingId, 'building_code'=>$building->code, 'telphone'=>$mobile, 'type'=>1));
                // 记录cookie
                set_cookie($cookieName, urlencode("building_id=$buildingId&mobile=$mobile"), 60*60*24);
                echo 'ok';
            // } else {
            //     echo '呼叫失败';
            // }
        } else {
            echo '楼盘错误';
        }
    }

    /**
     * 预约看房
     * @return string
     */
    public function kanfang() {
        $this->load->library('user_agent');
        $get = $this->input->get();
        $mobile = $get['mobile'];
        $buildingId = $get['building_id'];
        $phoneCode = isset($get['phone_code']) ? $get['phone_code'] : '';
        $is_mobile = $this->agent->is_mobile();
        // 加载模型
        $this->load->model('buildings/buildings_model');
        // 楼盘数据
        $building = $this->buildings_model->getBuildingById($buildingId);

        // 判断是否需要手机验证码功能，现在只有北京的项目有这个功能
        if ($this->isShowPhoneAuthCode($building->city_id, $mobile)) {
            if (empty($phoneCode)) {
                // if (!$is_mobile) $this->sendCode($mobile);
                exit('auth_code');
            } else {
                // 验证是否正确
                if (!$this->verifyPhoneCode($mobile, $phoneCode)) {
                    exit("验证码错误~");
                }
            }
            
        }

        if ($this->verifyMobile($mobile) && $building) {
            // 写记录
            $this->load->model('buildings/buildingsyuyue_model');
            $this->buildingsyuyue_model->insert(array('building_id'=>$buildingId, 'building_code'=>$building->code, 'telphone'=>$mobile, 'type'=>2));
            echo 'ok';
        } else {
            echo '号码错误';
        }
    }

    /**
     * 验证手机号规则
     * @param int $mobile 手机号码
    */
    public function verifyMobile($mobile) {
        $return = false;
        // 正则手机或固定电话
        $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        $isMob = "/^1[3-5,7,8]{1}[0-9]{9}$/";
        if(preg_match($isMob, $mobile) || preg_match($isTel, $mobile)) {
            $return = true;
        }
        return $return;
    }


    /**
     * 短信接口
     * @param  int $mobile  手机号码
     * @param  string $content 短信内容
     * @return boolean          
     */
    private function sendSMS($mobile, $content) {
        $post_url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
        $smsData = array(
            'account'=>'cf_shmkj',
            'password'=>'shmkj123',
            'mobile'=>$mobile,
            'content'=>$content,
        );
        if (is_fang90_server_name()) {
            $smsData['account'] = 'cf_youxwl';
            // $smsData['password'] = 'e10adc3949ba59abbe56e057f20f883e';
            $smsData['password'] = '85bff964ecbc5070b221b151158ba099';
        }
        $this->load->library('curl', $post_url);
        $this->curl->post($smsData);
        $returnStr = $this->curl->execute();
        if (!empty($returnStr)) {
            $obj = simplexml_load_string($returnStr);
            return $obj;
        }
    }

    /**
     * ajax 发送短信验证码给手机号
     */
    public function ajaxSendCode() {
        $get = $this->input->get();
        $mobile = $get['mobile'];
        $buildingCode = $get['building_code'];

        if (!$this->verifyMobile($mobile)) {
            echo json_encode(['status'=>'号码错误']);
            exit;
        }

        $rebackCode = $this->sendCode($mobile, $buildingCode);
        // 返回
        if($rebackCode->code == 2){
            $this->load->model('buildings/buildingsyuyue_model');
            $this->buildingsyuyue_model->insert(array('building_id'=>0, 'building_code'=>$buildingCode,'telphone'=>$mobile, 'type'=>0));
            echo json_encode(['status'=>'ok']);
        }else{
            echo json_encode(['status'=>'验证码发送失败~'.$rebackCode->code]);

        }
    }

    /**
     * ajax 验证 手机验证
     */
    public function ajaxVerifyPhoneCode() {
        $get = $this->input->get();
        $mobile = $get['mobile'];
        $phoneCode = $get['phone_code'];

        $result = $this->verifyPhoneCode($mobile, $phoneCode) ? 'ok' : 'error';
        if($result == 'ok'){
            $this->load->model('buildings/buildingsyuyue_model');
            $this->buildingsyuyue_model->insert(array('building_id'=>0, 'building_code'=>'tmpcode','telphone'=>$mobile, 'type'=>0));
        }
        echo json_encode(['status'=>$result]);
    }

    /**
     * 验证 手机验证码
     * @param  Int $mobile    手机号码
     * @param  Int $phoneCode 验证码
     * @return Boolean
     */
    private function verifyPhoneCode($mobile, $phoneCode) {
        $result = false;
        $phoneCodeArr = $this->phoneCodeArr();
        if (isset($phoneCodeArr[$mobile])) {
            if ($phoneCodeArr[$mobile]['code'] == $phoneCode) {
                $phoneCodeArr[$mobile]['status'] = 1;
                $this->session->set_userdata('phone_code', $phoneCodeArr);
                $result = true;
                // 更新记录
                $this->load->model("buildings/smsverifylog_model");
                $this->smsverifylog_model->update(['telphone'=>$mobile, 'code'=>$phoneCode], ['verified'=>1]);
            }
        }
        return $result;
    }

    // 发送短信验证码
    private function sendCode($mobile, $buildingCode = '') {
        $code = $this->creatCodeByRand();
        $phoneCode = $this->phoneCodeArr();
        $phoneCode[$mobile] = ['code'=>$code, 'status'=>0];
        $this->session->set_userdata('phone_code', $phoneCode);

        $content = "您的验证码为：".$code."，请在页面填写验证码完成验证。（如非本人操作，可不予理会）";
        $rebackCode = $this->sendSMS($mobile, $content);
        // 写记录
        $this->load->model("buildings/smsverifylog_model");
        $this->smsverifylog_model->insert(['telphone' => $mobile, 
                                            'code' => $code,
                                            'building_code' => $buildingCode,
                                            'return_code' => $rebackCode->code
                                            ]);
        return $rebackCode;
    }

    /**
     * 判断是否需要手机验证码功能
     * @param  int $cityId 城市ID
     * @return boolean
     */
    private function isShowPhoneAuthCode($cityId, $mobile) {
        // 判断是否需要手机验证码功能，现在只有北京的项目有这个功能
        $phoneCode = $this->phoneCodeArr();
        // $isYz = in_array($cityId, [52]);
        // $showAuthView = false;
        // if ($isYz) {
            $showAuthView = true;
            if (isset($phoneCode[$mobile])) {
                $showAuthView = $phoneCode[$mobile]['status'] == 0;
            }
        // }
        return $showAuthView;
    }

    private function phoneCodeArr() {
        if ($this->session->has_userdata('phone_code')) {
            return $this->session->userdata('phone_code');
        }
        return [];
    }

    //生成验证码
    private function creatCodeByRand(){
        $token = '';
        $len = 6;
        for ($i = 0; $i < $len; $i++)
        $token .= chr(mt_rand(48, 57));
        return $token;
    }

    /**
     * 400电话接口 异步调用
     * @param  int $mobile 手机号码
     * @param  int $ext    分机号
     * @return string         
     */
    private function ccic2($mobile, $ext, $userField, $clidNumber = '') {
        $ivrId = is_fang90_server_name() ? '1110' : '1106';
        $post_url = "http://puruan.ccic2.com/interface/entrance/OpenInterfaceEntrance";
        $data = array(
            'enterpriseId'=>'3002702',
            'userName'=>'admin',
            'pwd'=>'2a5ef8484e0fb13a76cf43389518baf5',
            // 'userName'=>'wz',
            // 'pwd'=>'c530504478b1f217c487c7eeeb38fa46',
            'interfaceType'=>'webCall',
            'customerNumber'=>$mobile,
            'paramNames'=>'extension',
            'paramTypes'=>'1',
            'extension'=>$ext,
            'sync'=>'0',
            'ivrId'=>$ivrId,
            'userField'=> $userField,
        );
        if (!empty($clidNumber)) {
            $data['clidNumber'] = $clidNumber;
        }
        $this->load->library('curl', $post_url);
        $this->curl->post($data);
        $returnJson = $this->curl->execute();
        return $returnJson;
    }

    public function captcha() {
        $this->load->library('captcha');
        $code = $this->captcha->getCaptcha();
        $this->session->set_userdata('captcha_code', $code);
        $this->captcha->showImg();
    }

    /**
     * 通过城市ID获取来电显示号码
     * @param  int $cityId 城市ID
     * @return string      号码
     */
    protected function clidNumber($cityId) {
        $numberArr['321'] = '02180206939'; // 上海
        $numberArr['77'] = '075521245185'; // 深圳
        $numberArr['52'] = '01089191187'; // 北京
        $numberArr['343'] = '02266337083'; // 天津
        $numberArr['244'] = '02462785052'; // 沈阳
        $numberArr['322'] = '02863154331'; // 成都
        $numberArr['220'] = '02566871530'; // 南京
        $numberArr['180'] = '02759568760'; // 武汉
        $numberArr['221'] = '051262914289'; // 苏州
        $numberArr['76'] = '02083530098'; // 广州
        if (isset($numberArr[$cityId])) {
            return $numberArr[$cityId];
        }
        return $numberArr['321'];
    }

    public function sessions() {
        // $this->session->unset_userdata('phone_code');
        dump($this->session->userdata());
        echo APPPATH.'cache/ci3_sessions';
    }

    /**
     * 新增楼盘事件数据
     * @return mixed
     */
    public function addEventLog($buildingLogId = null, $event = null, $buildingCode = null, $phone = null) {
        // 参数
        $get = $this->input->get();
        $buildingLogId = $buildingLogId ? : $get['view_building_log_id'];
        $event = $event ? : $get['event'];
        $buildingCode = $buildingCode ? : $get['building_code'];
        $phone = $phone ? : ((isset($get['phone']) && !empty($get['phone'])) ? $get['phone'] : '') ;
        $channel = $get['channel'];
        // 加载模型
        $this->load->model('buildings/buildingphonelog_model', 'buildingPhoneLog_model');
        $this->load->model('buildings/buildingeventlog_model', 'buildingEventLog_model');
        // 数据
        $this->load->library('user_agent');
        $platform = $this->agent->is_mobile ? 2 : 1;
        $id = get_building_event_log_id();
        $eventArr = array_flip(building_event_type());
        $event = $eventArr[$event];
        // $eventLogId = $this->buildingEventLog_model->insert(array('id'=>$id, 'building_log_id'=>$buildingLogId, 'event'=>$event, 'building_code'=>$buildingCode, 'platform'=>$platform));
        $this->buildingEventLog_model->set_table_name_create('');
        $eventLogTableName = $this->buildingEventLog_model->get_table();
        $this->buildingEventLog_model->db->query("INSERT INTO {$eventLogTableName} (`id`,`building_log_id`,`building_code`,`event`,`platform`,`created_on`) VALUES (?,?,?,?,?,now())", array($id,$buildingLogId,$buildingCode,$event,$platform), true);
        $returnArr['event_log_id'] = $id;
        if (!empty($phone)) { //in_array($event, array(1,2,3)) && 
            // 拨打电话事件,或者留下电话号码事件,记录电话号码
            $returnId = $this->buildingPhoneLog_model->insert(array('building_log_id'=>$buildingLogId, 'event_id'=>$id, 'telphone'=>$phone, 'event'=>$event, 'building_code'=>$buildingCode, 'channel_code'=>$channel, 'platform'=>$platform, 'ti_unique_id'=>$phone.time()));
            $returnArr['phone_log_id'] = $returnId;
        }
        // 记录日志
        $this->load->helper('cookie');
        $uniVal = get_cookie('udf_view_uni_code') ? : '';
        $logStr = date("Y-m-d H:i:s")."#e#{$uniVal}#{$event}";
        view_event_log($logStr);

        echo json_encode($returnArr);
    }

    /**
     * 更新浏览记录数据
     * @return mixed
     */
    public function viewLogUpdate() {
        // 参数
        $get = $this->input->get();
        $viewBuildingLogId = $get['view_building_log_id'];
        $viewLogTime = isset($get['view_log_time']) ? $get['view_log_time'] : '';
        $requestID = isset($get['request_id']) ? $get['request_id'] : '';
        if (empty($viewBuildingLogId) || empty($viewLogTime)) exit('参数错误');
        // 加载模型
        $this->load->model('buildings/viewbuildinglog_model');
        $this->viewbuildinglog_model->chip_date = date("Ymd", $viewLogTime);
        $data = ['leave_time'=>date("Y-m-d H:i:s")];
        if ($requestID) $data['request_id'] = $requestID;
        $this->viewbuildinglog_model->update($viewBuildingLogId, $data);
    }

    /**
     * 批量处理图片缩略图
     * @return mixed
     */
    public function imageView2() {
        // (1封面图\2楼盘照片\3楼盘特色图片\4户型图\5楼盘顶部图片)（1学校logo\2头图\3轮播图\4导航封面图）
        $this->load->model('buildings/photos_model');
        $photos = $this->photos_model->select("url,target_id,platform,type,sub_type")->where("url != '' AND deleted = 0 AND type = 1 AND sub_type = 5")->order_by("target_id")->find_all();
        dump($photos);exit();

        // 缩略图持久化
        require APPPATH.'third_party/Qiniu-7.0.7/autoload.php';
        // 公司账号
        $accessKey = '8Dr5iNDERxyj6P1cnHGlsmJxa5onjfnGl9gqzvS-';
        $secretKey = 'JMGXnHMLIVEgKSHY6jnx8HAwUs0QrPrWuKUoJSWZ';
        // 构建鉴权对象
        $auth = new Qiniu\Auth($accessKey, $secretKey);
        $bucket = 'udianfang';
        // $notifyUrl = 'http://375dec79.ngrok.com/notify.php';
        // $pipeline = 'pipeline_building_imageView2';
        $pfop = new Qiniu\Processing\PersistentFop($auth, $bucket);
        //要进行转码的转码操作。 http://developer.qiniu.com/docs/v6/api/reference/fop/av/avthumb.html
        $imageView2 = 'imageView2/0';
        foreach ($photos as $key => $val) {
            // if ($key > 10) {
            //     break;
            // }

            // echo $val->url.PHP_EOL;
            $key = $val->url;
            $fops = false;
            if ($val->platform == 2) {
                // 移动端
                // $fops = [//"{$imageView2}/w/1920/interlace/1|saveas/".base64_encode("$bucket:".$key."-large"), 
                //      //"{$imageView2}/w/2800/interlace/1|saveas/".base64_encode("$bucket:".$key."-medium_2x"), 
                //      "{$imageView2}/w/540/interlace/1|saveas/".base64_encode("$bucket:".$key."-small.540")];
            } else {
                // continue;
                // PC端
                $fops = [//"{$imageView2}/w/1920/interlace/1|saveas/".base64_encode("$bucket:".$key."-large"), 
                     //"{$imageView2}/w/2800/interlace/1|saveas/".base64_encode("$bucket:".$key."-medium_2x"), 
                     // "{$imageView2}/w/1400/interlace/1|saveas/".base64_encode("$bucket:".$key."-large.1400"), 
                     "{$imageView2}/w/2800/interlace/1|saveas/".base64_encode("$bucket:".$key."-medium.2x.2800"), 
                     //"{$imageView2}/w/1400/interlace/1|saveas/".base64_encode("$bucket:".$key."-medium.1400"), 
                     ];
            }
            // $exeReturn = $pfop->execute($key, $fops);
            // dump($exeReturn);
            if ($fops) {
                list($id, $err) = $pfop->execute($key, $fops);
                echo PHP_EOL."====> pfop avthumb result: ".PHP_EOL;
                if ($err != null) {
                    dump($err);
                } else {
                    echo "PersistentFop Id: $id".PHP_EOL;
                }
            }
        }
    }

    /**
     * 为一个楼盘在多个城市投放区分400分机号临时创建的函数
     * @return array
     */
    private function _ext_target_city($buildingId, $channel, $targetCity) {
        // 1638 天渠
        $ext[1638]['tq']['beijing'] = ['pc'=>(object)['number'=>10736], 'mobile'=>(object)['number'=>4000812062]];
        $ext[1638]['tq']['shanghai'] = ['pc'=>(object)['number'=>10737], 'mobile'=>(object)['number'=>4000265902]]; // 在用
        $ext[1638]['tq']['guangzhou'] = ['pc'=>(object)['number'=>10738], 'mobile'=>(object)['number'=>4000812096]];
        // 1638 百度
        $ext[1638]['baidu']['beijing'] = ['pc'=>(object)['number'=>10733], 'mobile'=>(object)['number'=>4006515039]];
        $ext[1638]['baidu']['shanghai'] = ['pc'=>(object)['number'=>10734], 'mobile'=>(object)['number'=>4006604922]]; // 在用
        $ext[1638]['baidu']['guangzhou'] = ['pc'=>(object)['number'=>10735], 'mobile'=>(object)['number'=>4000812061]];
        // 1638 腾讯新闻
        $ext[1638]['txxw']['beijing'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000196507]];
        $ext[1638]['txxw']['shanghai'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000676507]]; // 在用
        $ext[1638]['txxw']['guangzhou'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000155870]];
        // 1638 凤凰新闻
        $ext[1638]['fhxw']['shanghai'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000502609]]; // 在用
        // 1638 网易新闻
        $ext[1638]['wyxw']['shanghai'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000985901]]; // 在用
        // zaker
        $ext[1638]['zaker']['shanghai'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000265921]]; // 在用
        // 百度KA
        $ext[1638]['bdka']['shanghai'] = ['pc'=>(object)['number'=>10836], 'mobile'=>(object)['number'=>4000266182]]; // 在用
        // 今日头条
        $ext[1638]['jrtt']['shanghai'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000628901]]; // 在用
        // 网易2
        $ext[1638]['wyt']['shanghai'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4006903413]]; // 在用
        // 1638 默认
        $extNormal[1638] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>10739]];

        // // 1684 绿地·伦敦之巅 天渠
        // $ext[1684]['lj']['beijing'] = ['pc'=>(object)['number'=>10905], 'mobile'=>(object)['number'=>4000809073]];
        // $ext[1684]['lj']['shanghai'] = ['pc'=>(object)['number'=>10906], 'mobile'=>(object)['number'=>4006373550]];
        // // 1684 头条
        // $ext[1684]['ttjr']['beijing'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4000290683]];
        // $ext[1684]['ttjr']['shanghai'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4006929070]];
        // // 1684 腾讯新闻
        // $ext[1684]['txxw']['beijing'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4006353070]];
        // $ext[1684]['txxw']['shanghai'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4006131553]];
        // // 1684 天天理财
        // $ext[1684]['ttlc']['beijing'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4000625102]];
        // $ext[1684]['ttlc']['shanghai'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4000366185]];
        // // 1684 zaker
        // $ext[1684]['zaker']['beijing'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4000936509]];
        // $ext[1684]['zaker']['shanghai'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4000676185]];
        // // 1684 宝宝树
        // $ext[1684]['bbs']['beijing'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4000159065]];
        // $ext[1684]['bbs']['shanghai'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4000715708]];
        // // 1684 ydzx
        // $ext[1684]['ydzx']['beijing'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4000625109]];
        // $ext[1684]['ydzx']['shanghai'] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>4000622106]];
        // // 1684 dxtc
        // $ext[1684]['dxtc']['shanghai'] = ['pc'=>(object)['number'=>10942], 'mobile'=>(object)['number'=>4000151036]];
        // // 1684 默认
        // $extNormal[1684] = ['pc'=>(object)['number'=>10907], 'mobile'=>(object)['number'=>10907]];
        
        // 绿地-伦敦之巅10/26日 更新号码
        $extNormal[1684] = ['pc'=>(object)['number'=>11025], 'mobile'=>(object)['number'=>11025]]; //默认
        // 百度KA
        $ext[1684]['bdka']['shanghai'] = ['pc'=>(object)['number'=>10905], 'mobile'=>(object)['number'=>4006908750]];
        $ext[1684]['bdka']['beijing'] = ['pc'=>(object)['number'=>11045], 'mobile'=>(object)['number'=>4000186826]];
        // 1684 ydzx
        // $ext[1684]['ydzx']['shanghai'] = ['mobile'=>(object)['number'=>4000656093]];
        // 腾讯2  
        $ext[1684]['txt']['shanghai'] = ['mobile'=>(object)['number'=>4000250093]];
        $ext[1684]['txt']['beijing'] = ['mobile'=>(object)['number'=>4000628605]];
        // 兔博士APP  
        $ext[1684]['tbs']['shanghai'] = ['mobile'=>(object)['number'=>4000587615]];
        $ext[1684]['tbs']['beijing'] = ['mobile'=>(object)['number'=>4000568790]];
        // 灵集
        $ext[1684]['lj']['shanghai'] = ['mobile'=>(object)['number'=>4000656093]];
        $ext[1684]['lj']['beijing'] = ['pc'=>(object)['number'=>11046], 'mobile'=>(object)['number'=>4006373050]];
        // 头条
        $ext[1684]['ttjr']['shanghai'] = ['pc'=>(object)['number'=>11025], 'mobile'=>(object)['number'=>4000625619]];
        // 电信弹窗
        $ext[1684]['dxtc']['shanghai'] = ['pc'=>(object)['number'=>11025], 'mobile'=>(object)['number'=>4000280932]];



        // 绿地·悉尼nbh
        $extNormal[1702] = ['pc'=>(object)['number'=>11034], 'mobile'=>(object)['number'=>11034]]; //默认
        // 1702 百度ka
        $ext[1702]['bdka']['beijing'] = ['pc'=>(object)['number'=>11036], 'mobile'=>(object)['number'=>4006013137]];
        $ext[1702]['bdka']['shanghai'] = ['pc'=>(object)['number'=>11033], 'mobile'=>(object)['number'=>4000628925]];
        $ext[1702]['bdka']['shenzhen'] = ['pc'=>(object)['number'=>11038], 'mobile'=>(object)['number'=>4006377839]];
        // 1702 lj
        $ext[1702]['lj']['beijing'] = ['pc'=>(object)['number'=>11035], 'mobile'=>(object)['number'=>4000155870]];
        $ext[1702]['lj']['shanghai'] = ['pc'=>(object)['number'=>11032], 'mobile'=>(object)['number'=>4000696751]];
        $ext[1702]['lj']['shenzhen'] = ['pc'=>(object)['number'=>11037], 'mobile'=>(object)['number'=>4000196817]];
        // 1702 腾讯2
        $ext[1702]['txt']['beijing'] = ['pc'=>(object)['number'=>11034], 'mobile'=>(object)['number'=>4000679065]];
        $ext[1702]['txt']['shanghai'] = ['pc'=>(object)['number'=>11034], 'mobile'=>(object)['number'=>4000196507]];
        $ext[1702]['txt']['shenzhen'] = ['pc'=>(object)['number'=>11034], 'mobile'=>(object)['number'=>4000636805]];
        // 1702 兔博士APP
        $ext[1702]['tbs']['beijing'] = ['pc'=>(object)['number'=>11034], 'mobile'=>(object)['number'=>4000976805]];
        $ext[1702]['tbs']['shanghai'] = ['pc'=>(object)['number'=>11034], 'mobile'=>(object)['number'=>4000756817]];
        $ext[1702]['tbs']['shenzhen'] = ['pc'=>(object)['number'=>11034], 'mobile'=>(object)['number'=>4000277615]];
        // 1702 头条
        $ext[1702]['ttjr']['shanghai'] = ['pc'=>(object)['number'=>11034], 'mobile'=>(object)['number'=>4000861063]];
        // 1702 电信弹窗
        $ext[1702]['dxtc']['shanghai'] = ['pc'=>(object)['number'=>11034], 'mobile'=>(object)['number'=>4000609283]];

        if (isset($ext[$buildingId][$channel][$targetCity])) {
            return $ext[$buildingId][$channel][$targetCity];
        }
        return $extNormal[$buildingId];
    }

    //魔方网页
    private function magicPage($photos, $buildingId, $hv){

         $magic_session = $this->session->userdata('magic_data');
        //读取魔方网页session，没有就新创建规则
        if(isset($magic_session) && !empty($magic_session[$buildingId][$hv])){
            $magic_data = $magic_session[$buildingId][$hv];
            $pcPic = $photos['tstp']['pc'];
            //根据头图版本取顶部特色图片(桌面端)
            $photos['tstp']['pc'] = [];
            foreach ($magic_data['pc'] as $k => $v) {
                foreach ($pcPic as $key => $value) {
                    if($v == $value->id){
                         $photos['tstp']['pc'][] = $value;
                    }
                }
            }
            $mobilePic = $photos['tstp']['mobile'];
            //根据头图版本取顶部特色图片(手机端)
            $photos['tstp']['mobile'] = [];
            foreach ($magic_data['mobile'] as $k => $v) {
                foreach ($mobilePic as $key => $value) {
                    if($v == $value->id){
                         $photos['tstp']['mobile'][] = $value;
                    }
                }
            }
        }else{
            //特色图片魔方实现
            foreach ($photos['tstp']['pc'] as $key => $value) {
                if ($value->domain == 'fang90' || $value->category == 0) continue;
                $value->version_id = substr($value->version, 1);
                $value->name = building_pic_zone()[$value->category]."--".$value->version;
                $version_key = building_tspic_version()[$value->version_id];
                $tmp['pc'][$value->category][$version_key][] = $value;
            }
            foreach ($photos['tstp']['mobile'] as $key => $value) {
                if ($value->domain == 'fang90' || $value->category == 0) continue;
                $value->version_id = substr($value->version, 1);
                $value->name = building_pic_zone()[$value->category]."--".$value->version;
                $version_key = building_tspic_version()[$value->version_id];
                $tmp['mobile'][$value->category][$version_key][] =$value;
            }
            // 底部图片
            if (isset($tmp['pc'][2])) {
                $bottomPcImg = isset($tmp['pc'][2][$hv]) ? $tmp['pc'][2][$hv] : $tmp['pc'][2]['v1'];
                $bottomMobileImg = isset($tmp['mobile'][2][$hv]) ? $tmp['mobile'][2][$hv] : $tmp['mobile'][2]['v1'];
                unset($tmp['pc'][2]);
                unset($tmp['mobile'][2]);
            }
            // 顶部图片
            if (isset($tmp['pc'][1])) {
                if (isset($tmp['pc'][1][$hv])) {
                    $topPcImg = $tmp['pc'][1][$hv];
                    unset($tmp['pc'][1][$hv]);
                } else {
                    $topPcImg = $tmp['pc'][1]['v1'];
                    unset($tmp['pc'][1]['v1']);
                }
                if (isset($tmp['mobile'][1][$hv])) {
                    $topMobileImg = $tmp['mobile'][1][$hv];
                    unset($tmp['mobile'][1][$hv]);
                } else {
                    $topMobileImg = $tmp['mobile'][1]['v1'];
                    unset($tmp['mobile'][1]['v1']);
                }
            }
            foreach ($tmp['pc'] as $key => $value) {
                if($key == 1){
                    foreach ($value as $k1 => $v1) {
                        $tmp2['pc'][] = $value[$k1];
                        $tmp2['mobile'][] = $tmp['mobile'][$key][$k1];
                    }
                }else{
                    $version_tmp = array_rand($value,1);
                    $tmp2['pc'][] = $value[$version_tmp];
                    $tmp2['mobile'][] = $tmp['mobile'][$key][$version_tmp];
                }
            }
            //分类位置重排
            shuffle($tmp2['pc']);
            shuffle($tmp2['mobile']);
            $photos['tstp']['pc'] = [];
            $photos['tstp']['mobile'] = [];
            //头部
            foreach ($topPcImg as $key => $value) {
                $photos['tstp']['pc'][] = $value;
                $magic_t_data['pc'][] = $value->id;
            }
            foreach ($topMobileImg as $key => $value) {
                $photos['tstp']['mobile'][] = $value;
                $magic_t_data['mobile'][] = $value->id;
            }
            //特色图片
            foreach ($tmp2['pc'] as $key => $value) {
                foreach ($value as $k => $v) {
                    $photos['tstp']['pc'][] = $v;
                    $magic_t_data['pc'][] = $v->id;
                }
            }
            foreach ($tmp2['mobile'] as $key => $value) {
                foreach ($value as $k => $v) {
                    $photos['tstp']['mobile'][] = $v;
                    $magic_t_data['mobile'][] = $v->id;
                }
            }
            //底部
            if(isset($bottomPcImg) && !empty($bottomPcImg)){
                foreach ($bottomPcImg as $key => $value) {
                    $photos['tstp']['pc'][] = $value;
                    $magic_t_data['pc'][] = $value->id;
                }
                foreach ($bottomMobileImg as $key => $value) {
                    $photos['tstp']['mobile'][] = $value;
                    $magic_t_data['mobile'][] = $value->id;
                }
            }
            $magic_session[$buildingId][$hv] = $magic_t_data;
            $this->session->set_userdata('magic_data', $magic_session);            
        }
        return $photos;
    }

    /**
     * 特色图片多版本逻辑处理，取对应版本的图片
     * @param  array $photos
     * @param  string $v     版本号
     * @return array
     * @author zephan <zephanliu@gmail.com>
     */
    private function tstpVersion($photos, $v) {
        $tstp_pc = $photos['tstp']['pc'];
        $tstp_mobile = $photos['tstp']['mobile'];
        $photos['tstp']['pc'] = [];
        $photos['tstp']['mobile'] = [];
        foreach ($tstp_pc as $key => $val) {
            if($val->version == $v) $photos['tstp']['pc'][] = $val;
        }
        foreach ($tstp_mobile as $key => $val) {
            if($val->version == $v) $photos['tstp']['mobile'][] = $val;
        }
        if(empty($photos['tstp']['pc'])){
            $photos['tstp']['pc'][] = $tstp_pc[0];
            $photos['tstp']['mobile'][] = $tstp_mobile[0];
        }
        return $photos;
    }
    /**
     * 推广页PC端400外呼接口
     * @author fengchen <fengchen@usuretech.com>
     * @time 2016/11/3
     */
    public function ccicForCampaign(){
        $get = $this->input->get();
        $mobile = $get['mobile'];
        $telExt = $get['tel_ext'];
        $campaignId = $get['campaignId'];
        $campaignCode = $get['campaignCode'];
        $cookieName = 'campaign_ccic2_call_'.$campaignId.'_'.$mobile;
        // 加载模型
        $this->load->helper('cookie');

        if (!$this->verifyMobile($mobile)) {
            echo '号码错误';
            exit();
        }

        // 判断是否需要手机验证码功能
        if ($this->isShowPhoneAuthCode(321, $mobile)) {
            // $this->sendCode($mobile);
            exit('auth_code');
        }

        // 400 异步调用
        $userField = "from=tuiguangye";
        $clidNumber = $this->clidNumber(321); //默认上海的外显号码
        $returnJson = $this->ccic2($mobile, $telExt, $userField, $clidNumber);

        // 成功，写记录
        $this->load->model('buildings/buildingsyuyue_model');
        $this->buildingsyuyue_model->insert(array('building_id'=>0, 'building_code'=>$campaignCode, 'telphone'=>$mobile, 'type'=>1));
        // 记录cookie
        set_cookie($cookieName, urlencode("tuiguangye_id=$campaignId&mobile=$mobile"), 60*60*24);
        echo 'ok';
    }
    /**
     * 预约看房推广页
     * @return string
     */
    public function kanfangForCampaign() {
        $this->load->library('user_agent');
        $get = $this->input->get();
        $mobile = $get['mobile'];
        $campaignId = $get['campaignId'];
        $campaignCode = $get['campaignCode'];
        $phoneCode = isset($get['phone_code']) ? $get['phone_code'] : '';

        // 判断是否需要手机验证码功能，现在只有北京的项目有这个功能
        if ($this->isShowPhoneAuthCode(321, $mobile)) {
            if (empty($phoneCode)) {
                // if (!$is_mobile) $this->sendCode($mobile);
                exit('auth_code');
            } else {
                // 验证是否正确
                if (!$this->verifyPhoneCode($mobile, $phoneCode)) {
                    exit("验证码错误~");
                }
            }
            
        }
        if ($this->verifyMobile($mobile)) {
            // 写记录
            $this->load->model('buildings/buildingsyuyue_model');
            $this->buildingsyuyue_model->insert(array('building_id'=>0, 'building_code'=>$campaignCode, 'telphone'=>$mobile, 'type'=>2));
            echo 'ok';
        } else {
            echo '号码错误';
        }
    }
    /**
     * [dataReceive 接受前端数据，传ERP库]
     * @author [fengchen]
     * @DateTime 2017-02-28T11:34:44+0800
     * @return   [type]                   [description]
     */
    public function dataReceive(){

        $get = $this->input->get();
        $mobile = $get['mobile'];
        $campaignCode = $get['campaignCode'];
        // 首先对其号码进行验证
        if(!empty($mobile) && !empty($campaignCode)){
            $this->load->model('buildings/buildingsyuyue_model');
            $where = ['telphone'=>$mobile, 'building_code'=>"tmpcode"];
            $result = true;
            if(isset($get['type']) && $get['type'] == 10){
                $result = $this->buildingsyuyue_model->find_by($where);
            }
            if($result){
                // 数据正确 传数据逻辑开始
                $this->load->library('curl');
                // 必须参数
                $getData['mobile'] = $mobile;
                $getData['projectNo'] = $get['projectNo'];
                $getData['channel'] = $get['channel'];
                // 非必须参数
                $getData['cookie'] = $get['cookie'];
                $getData['page'] = $get['page'];
                $getData['ip'] = $get['ip'];
                $getData['type'] = $get['type'];

                $get_url = 'http://test.qwzt.net:8080/dms/submitcustomer/custAction?'.http_build_query($getData, NULL, '&');
                // $get_url = 'http://172.16.0.50:8077/dms/submitcustomer/custAction?'.http_build_query($getData, NULL, '&');
                $this->curl->_simple_call('get',$get_url);
                
            }else{
                // 非法请求
                echo json_encode(['status'=>'error', 'msg'=>'提交失败，非法请求']);
                exit();
            }
        }else{
            // 非法请求
            echo json_encode(['status'=>'error', 'msg'=>'提交失败，非法请求']);
            exit();
            
        }
    }
}